<template>
    <div class="l-from-body" style="padding:8px 48px 8px 48px;" >
        <el-divider content-position="left">我的头像</el-divider>
        <el-avatar :size="100" fit="cover" :src="imageUrl || avatar">
             <img :src="`${rootUrl}img/admin/head.png`"/>
        </el-avatar>
        <el-upload
       
        ref="upload"
        :auto-upload="false"
        accept=".jpeg,.jpg,.png"
        :action="`${this.apiUrl}organization/user/img/${loginInfo.f_UserId}?token=${token}`"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        :on-change="handleChange"
        :on-success="handleAvatarSuccess"
        >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button :disabled="saveBtnDisabled" style="margin-left: 10px;" size="small" type="success" @click="submitUpload" :loading="loading" >保存修改</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
        </el-upload>
    </div>
</template>

<script>
export default {
    name: "user-head",
    data () {
        return {
            imageUrl: '',
            saveBtnDisabled:true,
            loading:false
        };
    },
    computed: {
        avatar:function(){
            return this.loginInfo.f_HeadIcon ? `${this.apiUrl}organization/user/img/${this.loginInfo.f_HeadIcon}?token=${this.token}` : `${this.rootUrl}img/admin/head.png`
        }
    },
    created () { 
    },
    methods: {
    submitUpload() {
        this.loading = true;
        this.$refs.upload.submit();
    },
    handleChange(file){
        this.imageUrl = window.URL.createObjectURL(file.raw);
        this.saveBtnDisabled = false;
    },
    handleAvatarSuccess(res) {
        if(res.code == 200){
            this.$message({
                type: 'success',
                message: '保存修改成功!'
            });

            this.loginInfo.f_HeadIcon = '';
            this.$nextTick(()=>{
                this.loginInfo.f_HeadIcon = res.data;
            })
            this.saveBtnDisabled = true;
        }
        else{
            this.$message({
                type: 'error',
                message: res.info
            });
        }
        this.loading = false;
    },
    beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            this.loading = false;
            this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
        }
    } 
};
</script>